<?php

namespace app\command\service\step;

use think\facade\Db;

class CheckLinks
{
    public static function run($taskData, $db)
    {
        $links = $db->select('url,type,position')->from(env('database.prefix') . 'link')
            ->where("is_del=1 AND website_id = " . $taskData['websiteId'])->query();

        $inLinks = [];
        $outLinks = [];
        foreach ($links as $vo) {

            if ($vo['type'] == 1) {

                try {
                    $html = file_get_contents($vo['position']);
                    if (strstr($html, $vo['url']) == false) {
                        $inLinks['linksHave'][] = [
                            'status' => 2,
                            'msg' => $vo['position'] . '的友链已经被删除'
                        ];
                    } else {
                        $inLinks['linksHave'][] = [
                            'status' => 1,
                            'msg' => $vo['position'] . '的友链正常显示'
                        ];

                        // 检测nofollow
                        $html = \phpQuery::newDocument($html);
                        if ($html['a[href="' . $vo['url'] . '"]']->attr('rel') === 'nofollow') {
                            $inLinks['nofollow'][] = [
                                'status' => 2,
                                'msg' => $vo['position'] . '的友链添加了nofollow'
                            ];
                        } else {
                            $inLinks['nofollow'][] = [
                                'status' => 1,
                                'msg' => $vo['position'] . '的友链属性正常'
                            ];
                        }
                    }
                } catch (\Exception $e) {
                    $inLinks['linksHave'][] = [
                        'status' => 2,
                        'msg' => $vo['position'] . '无法访问'
                    ];
                }
            } else if ($vo['type'] == 2)  {

                try {
                    file_get_contents($vo['url']);

                    $outLinks['linksHave'][] = [
                        'status' => 1,
                        'msg' => $vo['url'] . '可以正常访问'
                    ];
                } catch (\Exception $e) {
                    $outLinks['linksHave'][] = [
                        'status' => 2,
                        'msg' => $vo['url'] . '无法访问'
                    ];
                }
            }
        }

        $analysis = [
            'inlinks' => $inLinks,
            'outlinks' => $outLinks
        ];

        return  $analysis;
    }
}